import React, { useRef } from "react";

const styles = { h1: { color: "blueviolet" } };
function HelloWorld({ msg, children }) {
  const domRef = useRef();
  const handleClick = () => {
    const event = new CustomEvent("myEvent", {
      detail: { msg },
    });
    // 获取自定义元素并派发事件
    const customElement = domRef.current?.getRootNode().host;
    if (customElement) {
      customElement.dispatchEvent(event);
    }
  };

  return (
    <div ref={domRef}>
      <h1 style={styles.h1}>Hello, {msg}</h1>
      <button onClick={handleClick}>发送事件</button>
      {children}
    </div>
  );
}

export default HelloWorld;
